import axios from "axios";
import { ElMessage } from "element-plus";

import { useUserStore } from "@/stores/user";

import router from '@/router'


const instance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 16000
})

// 拦截器

instance.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    const {userInfo:{token}} = useUserStore()
    // console.log(token);
    if(token) {
        // 2. 按照后端的要求拼接token数据
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, e => Promise.reject(e))

instance.interceptors.response.use(res => {
    // console.log(res)
    return res.data
}, err => {
    ElMessage({
        type: 'warning',
        message: err.response.data.message
    })

    // 401token失效处理
    // 1. 清除本地用户数据
    // 2. 跳转登录页
    const {clearUserInfo} = useUserStore()
    if (err.response.status === 401) {
        clearUserInfo()
        router.replace('/login')
    }
    return Promise.reject(err)
})

export default instance